package com.allen.app.common.utils;

import ch.qos.logback.classic.gaffer.PropertyUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * Description:class工具类
 *
 * @author Limiaojun
 * @date 2017/9/28 10:23
 * @version 1.0
 * @since JDK 1.8
 */
@Slf4j
@UtilityClass
public class ClassUtil {

    /**
     * 构建空字符串null.
     * @param object  object
     * @author Limiaojun
     * @date 2020/1/9 10:53
     */
    public void buildEmptyStrToNull(Object object) {
        if (Objects.isNull(object)) {
            return;
        }
        if (object instanceof Map) {
            //noinspection unchecked
            Map<String, Object> mapParam = ((Map<String, Object>) object);
            for (Entry<String, Object> entry : mapParam.entrySet()) {
                if (entry.getValue() instanceof String && StrUtil.isBlank(Convert.toStr(entry.getValue()))) {
                    mapParam.put(entry.getKey(), null);
                }
            }
            return;
        }

        Class<?> clazz = object.getClass();
        Try.unchecked(()-> {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (!"serialVersionUID".equals(field.getName())) {

                    Object fieldValue = ReflectUtil.getFieldValue(object, field);
                    if (fieldValue instanceof String && StrUtil.isBlank(Convert.toStr(fieldValue))) {
                        ReflectUtil.setFieldValue(object,field,null);
                    }

                }
            }
        });

    }
}
